import os
import requests
from lxml import etree
import multiprocessing
from multiprocessing import Pool,freeze_support
import numpy as np

headers = {'User-Agent':"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36", "Referer": "https://www.meitulu.com"}

def downloadimg(id):
    #dir=listurl[0].split('/')[-2]
    dir="k:/girls/"+id+"/"

    if not os.path.exists(dir):  ##如果没有这个文件夹的话，创造并进入
        os.makedirs(dir)  ##创建一
    ## https://www.meitulu.com/img.html?img=https://mtl.xtpxw.com/images/img/13586/1.jpg
    nums=getPages(id)

    urls=makeUrls(id,int(nums))
    for url in urls:
        dowloadheaders = {
            'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",

            }
        ##上面美图录喜欢修改host
       # url="https://img.onvshen.com:85/gallery/23100/32147/s/001.jpg";
        response = requests.get(url, headers=dowloadheaders, allow_redirects=False)
        imgname = url.split('/')[-1]
        path=dir+imgname

        with open(path, 'wb')as img:
            img.write(response.content)

def makeUrls(id,n):
    nums=[]
    urls=[]
    t=n*3
    for i in range(t):
        nums.append(str(i).rjust(3, '0'))
    #url="https://img.onvshen.com:85/gallery/23100/"+id+"/s/"+nums[i]+".jpg"
    for i in range(t):
        urls.append("https://img.onvshen.com:85/gallery/23100/"+id+"/s/"+nums[i]+".jpg")

    #0号图片的url比较特殊
    urls[0]="https://img.onvshen.com:85/gallery/23100/"+id+"/s/0.jpg"
    return urls


#print(makeUrls("234",14))

def getPages(id):
    url="https://m.nvshens.net/g/"+id+"/1.html"
    response = requests.get(url, headers=headers, allow_redirects=False)
    html = etree.HTML(response.text)
    n=html.xpath('//span[@class="page"]/text()')
    print("本页面有：")
    num=n[0].split('/')[-1]
    print(num)
    return num

def getImgUrl(id):
    url="https://m.nvshens.net/g/"+id+"/1.html"
    response = requests.get(url, headers=headers, allow_redirects=False)
    html = etree.HTML(response.text)
    result = html.xpath('//img/@src')
    n=html.xpath('//div[@class ="ck-parent-div"]')

    print(result)
    return n
#getPages("32274")
downloadimg("33198")
# getImgUrl("32454")

